from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.select import Select
from time import sleep
import sys
from random import random

ByXpath=By.XPATH

def opt_currency_type(symbol):
    if symbol=='GBP':
        value="英镑"
    elif symbol=='HKD':
        value="港币"
    elif symbol=='USD':
        value="美元"
    elif symbol=='CHF':
        value="瑞士法郎"
    elif symbol == 'DEM':
        value="德国马克"
    elif symbol == 'FRF':
        value="法国法郎"
    elif symbol == 'SGD':
        value="新加坡元"
    elif symbol == 'SEK':
        value="瑞典克朗"
    elif symbol == 'DKK':
        value="丹麦克朗"
    elif symbol == 'NOK':
        value="挪威克朗"
    elif symbol == 'JPY':
        value="日元"
    elif symbol == 'CAD':
        value="加拿大元"
    elif symbol == 'AUD':
        value="澳大利亚元"
    elif symbol == 'EUR':
        value="欧元"
    elif symbol == 'MOP':
        value="澳门元"
    elif symbol == 'PHP':
        value="菲律宾比索"
    elif symbol == 'THP':
        value="泰国铢"
    elif symbol == 'NZD':
        value="新西兰元"
    elif symbol == 'KRW':
        value="韩国元"
    elif symbol == 'SUR':
        value="卢布"
    elif symbol == 'RM':
        value="林吉特"
    elif symbol == 'TWD':
        value="新台币"
    elif symbol=='ESP':
        value="西班牙比塞塔"
    elif symbol == 'ITL':
        value="意大利里拉"
    elif symbol == 'NLG':
        value="荷兰盾"
    elif symbol == 'BEF':
        value="比利时法郎"
    elif symbol == 'FIM':
        value="芬兰马克"
    elif symbol == 'INR':
        value="印度卢比"
    elif symbol == 'IDR':
        value="印尼卢比"
    elif (symbol == 'BRL') or (symbol == 'BRC'):
        value="巴西里亚尔"
    elif symbol == 'DHS':
        value="阿联酋迪拉姆"
    elif symbol == 'ZAR':
        value="南非兰特"
    elif symbol == 'SAR':
        value="沙特里亚尔"
    elif symbol == 'TRL':
        value="土耳其里拉"
    else:
        print('没有找到这个货币')
        sys.exit(0)
    return value

def transform_date(date):
    return date[:4]+'-'+str(int(date[4:6]))+'-'+date[6:]

def init_option(traceless=True,show_img='true',prohibit_javascript=False,width=None,height=None):
    option = webdriver.ChromeOptions()  # 初始化Chrome

    option.binary_location=r'C:\Users\Administrator\AppData\Roaming\360se6\Application\360se.exe'#C:\Users\li\AppData\Roaming\360se6\Application\360se.exe

    option.add_argument('--no-sandbox')#最高权限
    #option.add_argument('--headless')#浏览器不提供可视化页面（无头模式）. linux下如果系统不支持可视化不加这条会启动失败
    option.add_argument('--disable-gpu')#禁用GPU加速,谷歌文档提到需要加上这个属性来规避bug

    option.add_argument("disable-web-security")# 关闭安全策略
    option.add_argument("--disable-blink-features=AutomationControlled")
    option.add_argument('disable-infobars')# 禁止策略化

    option.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36')  # 设置User-Agent属性,配置对象添加替换User-Agent的命令Mozilla/5.0 HAHA

    option.add_experimental_option('excludeSwitches', ['enable-automation'])  # 开发者模式，不提示“Chrome正受到自动测试软件控制”
    option.add_experimental_option('useAutomationExtension', False)#去掉提示以开发者模式调用

    if width==None or height==None:
        option.add_argument('--start-maximized')  # 最大化运行（全屏窗口）,不设置，取元素会报错
        #print('设置最大窗口')
    else:
        option.add_argument(f'--window-size={width},{height}')  # 设置浏览器分辨率（窗口大小）

    if traceless:
        option.add_argument('--incognito')  # 隐身模式（无痕模式）

    if show_img=='false':
        #print('不加载图片,可以加快爬取非图片数据的速度')
        option.add_argument('blink-settings=imagesEnabled=false')  # 加载图片
    #option.add_argument(f'blink-settings=imagesEnabled={show_img}')#不加载图片

    if prohibit_javascript:
        print('禁用JavaScript')
        option.add_argument('--disable-javascript')  # 禁用javascript

    desired_capabilities = DesiredCapabilities.CHROME  # 修改页面加载策略
    desired_capabilities["pageLoadStrategy"] = "none"  # 注释这两行会导致最后输出结果的延迟，即等待页面加载完成再输出

    return option

def driver_Init(options,wait_time=10):
    driver = webdriver.Chrome(chrome_options=options,executable_path=r'E:\program\PyCharmProjects\auto\chromedriver.exe')
    wait = WebDriverWait(driver, wait_time)
    driver.maximize_window()  # 全屏
    try:
        driver.get('http://www.baidu.com')
    except Exception as e:
        driver.quit()
        print(e)
        raise
    sleep(1)
    return driver, wait

def open_url(driver,url,error=0):
    try:
        driver.get(url)
    except:
        sleep(10)
        try:
            driver.get(url)
            print('第一次重新打开网页')
        except:
            sleep(30)
            try:
                driver.get(url)
                print('第二次重新打开网页')
            except:
                sleep(60)
                try:
                    driver.get(url)
                    print('第三次重新打开网页')
                except:
                    sleep(150)
                    try:
                        driver.get(url)
                        print('第四次重新打开网页')
                    except:
                        sleep(500)
                        try:
                            driver.get(url)
                            print('第五次重新打开网页')
                        except:
                            print('网速慢，无法打开网页')
                            error+=1

    return error

if __name__ == '__main__':
    date = transform_date(sys.argv[1])
    symbol = sys.argv[2]
    money=opt_currency_type(symbol)
    option=init_option(show_img='false',prohibit_javascript=False)
    driver,wait=driver_Init(option,30)
    url='https://srh.bankofchina.com/search/whpj/search_cn.jsp'
    open_url(driver,url)
    sleep(3)
    #print('打开网页')
    open_url(driver, url)
    #sleep(3)
    driver.refresh()#如果浏览器没反应需要切换为极速模式，再刷新
    sleep(5)
    #print('刷新网页')
    js=f'document.getElementsByClassName("search_ipt")[1].value="{date}"'
    driver.execute_script(js)
    js = f'document.getElementsByClassName("search_ipt")[2].value="{date}"'
    driver.execute_script(js)
    #print('找到输入框')
    sleep(2)
    #print('输入完毕')
    bar=driver.find_element(By.XPATH,"//select[@name='pjname']")
    select=Select(bar)
    #print('点击菜单栏')
    sleep(2)
    select.select_by_value(money)
    #print('点击菜单项')
    sleep(1)
    js = 'document.getElementsByClassName("search_btn")[1].click()'
    driver.execute_script(js)
    #print('搜索')
    sleep(3)
    try:
        page_line=driver.find_element(ByXpath,'//ol/li').text
    except:
        page_line=None
    if page_line!=None:
        print(page_line)
        page=int(page_line.replace('共','').replace('页',''))
    else:
        page=1
    with open('result.txt', 'a',encoding='utf-8') as f:
        for p in range(1,page+1):
            items=driver.find_elements(ByXpath,"//tr/td")#tr[@class='odd']
            i=1
            j=1
            for item in items:
                if j>8:
                    item=item.text.strip()
                    if i==4:#现汇卖出价
                        price=item
                    elif i==7:#时间
                        time=item
                        #print(money,price,time)
                        f.write(f'{money} {price} {time}\n')
                        i=0
                    i+=1
                else:
                    j+=1
            if page!=1 and p!=page:
                #js = 'document.getElementByClassName("//li[@class="turn_next"]").click();'
                #driver.execute_script(js)
                try:
                    driver.find_element(ByXpath,'//li[@class="turn_text"]').click()
                except Exception as e:
                    print(e)
                    sleep(5)
                    try:
                        driver.find_element(ByXpath, '//li[@class="turn_next"]').click()
                    except Exception as e:
                        print(e)
                        sleep(10)
                        try:
                            driver.find_element(ByXpath, '//li[@class="turn_next"]').click()
                        except Exception as e:
                            print(e)
                            sleep(30)
                sleep(2.5+random())

    #print('爬取完毕')
    print(price)

    driver.quit()